package com.example.shopingcenter.DateBase;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import com.example.shopingcenter.enity.User;

public class LoginDbHelper extends SQLiteOpenHelper {

    private static final String DB_NAME="user_database.db";
    private static final int DATABASE_VERSION = 1;
    private static  final String TABLE_NAME="users";
    public  static LoginDbHelper loginDbHelper=null;


    public LoginDbHelper(@Nullable Context context) {
        super(context, DB_NAME, null, DATABASE_VERSION);

    }

    public static LoginDbHelper getInstance(Context context){
          if (loginDbHelper==null){
              loginDbHelper=new LoginDbHelper(context);
          }
          return loginDbHelper;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
                "("

                +"name VARCHAR  NOT NULL,"
                + "password VARCHAR NOT NULL" +");";

           db.execSQL(sql);


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    }

    public boolean register(User user){

        SQLiteDatabase db = getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put("name",user.getName());
        values.put("password",user.getPassword());

        long reslut=db.insert("users",null,values);
        if (reslut == -1) {
            return false;
        } else {
            return true;
        }
    }

    public boolean login(String name,String password){
        SQLiteDatabase database = getReadableDatabase();

        boolean result;

        Cursor users=database.query
                (TABLE_NAME,null, "name like ?", new String[]{name},
                        null, null,null);
        if (users!=null){
            while (users.moveToNext()){
                String reallyPwd=users.getString(1);
                result=reallyPwd.equals(password);
                return result;
            }
        }
        return false;
    }
}
